// 模型训练页面
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Layout, Card, Form, Input, Select, Button, Table, message, Space, Typography, Tag, Divider, Modal, Tabs, Progress, Radio, Upload, Row, Col } from 'antd';
import { PlusOutlined, DeleteOutlined, SaveOutlined, PlayCircleOutlined, ToolOutlined, FileTextOutlined, PauseOutlined, UploadOutlined } from '@ant-design/icons';
import { mockService } from '../services/mockService';
import type { Job, FeatureView, Model } from '../types';
import { formatDateTime } from '../utils/fileUtils';
import FeatureFlowCanvas from '../components/FeatureFlowCanvas';
import JobList from '../components/JobList';
import * as yaml from 'js-yaml';

const { Content } = Layout;
const { Text, Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const TrainingPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('1');
  
  // 模型训练页签相关状态
  const [jobs, setJobs] = useState<Job[]>([]);
  const [models, setModels] = useState<Model[]>([]);
  const [currentJob, setCurrentJob] = useState<Job | null>(null);
  const [loading, setLoading] = useState(false);
  const [createForm] = Form.useForm();
  const [featureViews, setFeatureViews] = useState<FeatureView[]>([]);
  const [flowData, setFlowData] = useState<any>(undefined);
  const [yamlContent, setYamlContent] = useState<string>('');
  const [logs, setLogs] = useState<string[]>([
    '[2023-05-15 10:30:15] 开始模型训练任务...',
    '[2023-05-15 10:30:16] 加载训练数据集',
    '[2023-05-15 10:30:20] 数据预处理完成',
    '[2023-05-15 10:30:25] 初始化模型参数',
    '[2023-05-15 10:30:30] 开始第1轮训练',
    '[2023-05-15 10:30:45] 第1轮训练完成，准确率: 0.75',
    '[2023-05-15 10:30:46] 开始第2轮训练',
    '[2023-05-15 10:31:00] 第2轮训练完成，准确率: 0.78',
    '[2023-05-15 10:31:01] 开始第3轮训练'
  ]);
  const [isRunning, setIsRunning] = useState(false);
  
  // 创建任务模态框相关状态
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [trainingMode, setTrainingMode] = useState<'visual' | 'advanced'>('visual');
  const [useBaselineModel, setUseBaselineModel] = useState(false);
  const [selectedBaselineModel, setSelectedBaselineModel] = useState<string | null>(null);
  const [scriptFile, setScriptFile] = useState<File | null>(null);
  
  // 训练详情页签相关状态
  const [selectedJob, setSelectedJob] = useState<Job | null>(null);
  const [showSaveModelModal, setShowSaveModelModal] = useState(false);
  const [modelForm] = Form.useForm();
  
  // 加载数据
  useEffect(() => {
    loadInitialData();
  }, []);

  // 轮询更新运行中的任务状态和日志
  useEffect(() => {
    // 只有当有任务在运行时才启动轮询
    if (currentJob && currentJob.status === 'running') {
      const interval = setInterval(async () => {
        try {
          const jobsRes = await mockService.jobs.getAll();
          if (jobsRes.success && jobsRes.data) {
            // 查找当前运行的任务
            const updatedJob = jobsRes.data.find(job => job.id === currentJob.id);
            if (updatedJob) {
              // 更新currentJob状态
              setCurrentJob(updatedJob);
              // 更新日志
              setLogs(updatedJob.logs || []);
            }
          }
        } catch (error) {
          console.error('轮询更新任务状态失败:', error);
        }
      }, 2000); // 每2秒轮询一次

      // 清理函数
      return () => clearInterval(interval);
    }
  }, [currentJob]);

  const loadInitialData = async () => {
    try {
      setLoading(true);
      // 加载特征视图
      const featureViewsRes = await mockService.featureViews.getAll();
      if (featureViewsRes.success && featureViewsRes.data) {
        setFeatureViews(featureViewsRes.data);
      }
      
      // 加载作业
      const jobsRes = await mockService.jobs.getAll();
      if (jobsRes.success && jobsRes.data) {
        setJobs(jobsRes.data);
      }
      
      // 加载模型
      const modelsRes = await mockService.models.getAll();
      if (modelsRes.success && modelsRes.data) {
        setModels(modelsRes.data);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('数据加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 将FlowData转换为YAML - 使用 useMemo 优化
  const yamlContentMemo = useMemo(() => {
    try {
      if (!flowData || !flowData.nodes || !flowData.connections) {
        return '# 暂无工作流配置';
      }
      const yamlObj = {
        workflow: {
          nodes: flowData.nodes.map((node: any) => ({
            id: node.id,
            type: node.type,
            name: node.name,
            properties: node.properties || {}
          })),
          connections: flowData.connections.map((conn: any) => ({
            from: conn.source,
            to: conn.target,
            sourceHandle: conn.sourceHandle,
            targetHandle: conn.targetHandle
          }))
        }
      };
      return yaml.dump(yamlObj, { indent: 2 });
    } catch (error) {
      console.error('生成YAML失败:', error);
      return '# YAML生成错误';
    }
  }, [flowData]);

  useEffect(() => {
    if (currentJob) {
      setFlowData(currentJob.flowData || undefined);
      setLogs(currentJob.logs || []);
    } else {
      setFlowData(undefined);
      setYamlContent('# 暂无工作流配置');
      setLogs([]);
    }
  }, [currentJob]);
  
  // 使用 useMemo 的结果来更新 YAML 内容
  useEffect(() => {
    setYamlContent(yamlContentMemo);
  }, [yamlContentMemo]);

  // 保存流程数据 - 使用防抖优化
  const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
  
  // 处理流程数据变化
  const handleFlowChange = useCallback(async (newFlowData: any) => {
    setFlowData(newFlowData);
    
    // 清除之前的保存定时器
    if (saveTimerRef.current) {
      clearTimeout(saveTimerRef.current);
    }
    
    // 延迟保存，避免频繁保存
    if (currentJob) {
      saveTimerRef.current = setTimeout(async () => {
        try {
          await mockService.jobs.update(currentJob.id, { flowData: newFlowData });
        } catch (error) {
          console.error('保存流程数据失败:', error);
        }
      }, 1000); // 1秒后保存
    }
  }, [currentJob]);

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (saveTimerRef.current) {
        clearTimeout(saveTimerRef.current);
      }
    };
  }, []);

  // 处理创建任务
  const handleCreateJob = () => {
    setCreateModalVisible(true);
    createForm.resetFields();
    setTrainingMode('visual');
    setScriptFile(null);
  };
  
  // 处理保存模型
  const handleSaveModel = async (values: any) => {
    const jobToShow = selectedJob || {
      id: 'sample-1',
      name: '客户流失预测模型训练',
      type: 'training',
      status: 'completed',
      featureViewId: '1',
      modelConfig: {
        modelType: 'XGBoost',
        hyperparameters: {
          learning_rate: 0.1,
          max_depth: 6,
          n_estimators: 100,
          subsample: 0.8
        }
      },
      createdAt: new Date(Date.now() - 86400000).toISOString(),
      updatedAt: new Date().toISOString(),
      metrics: {
        accuracy: 0.87,
        precision: 0.85,
        recall: 0.82,
        f1Score: 0.83,
        auc: 0.91
      }
    };
    
    try {
      setLoading(true);
      
      const modelData = {
        name: values.name,
        version: parseInt(values.version),
        description: values.description,
        jobId: jobToShow.id,
        metrics: jobToShow.metrics || {},
        config: jobToShow.modelConfig
      };

      // 检查是否已存在相同名称和版本的模型
      const existingModels = await mockService.models.getAll();
      if (existingModels.success && existingModels.data) {
        const duplicate = existingModels.data.find(
          model => model.name === values.name && model.version === parseInt(values.version)
        );
        
        if (duplicate) {
          message.error('已存在相同名称和版本的模型，请修改版本号');
          return;
        }
      }

      const response = await mockService.models.save(modelData);
      
      if (response.success && response.data) {
        message.success('模型保存成功！');
        setShowSaveModelModal(false);
        modelForm.resetFields();
      } else {
        message.error(response.error || '模型保存失败');
      }
    } catch (error) {
      message.error('模型保存失败，请重试');
      console.error('错误:', error);
    } finally {
      setLoading(false);
    }
  };
  
  // 提交创建任务
  const handleCreateSubmit = async (values: any) => {
    try {
      setLoading(true);
      
      // 构建模型配置
      const modelConfig: any = {
        modelType: trainingMode === 'visual' ? 'VisualWorkflow' : 'CustomScript',
        hyperparameters: {}
      };
      
      // 如果使用基线模型，添加到配置中
      if (useBaselineModel && selectedBaselineModel) {
        modelConfig.baselineModel = selectedBaselineModel;
      }
      
      // 如果是高级模式，添加脚本信息
      if (trainingMode === 'advanced' && scriptFile) {
        modelConfig.customScript = scriptFile.name;
      }
      
      const response = await mockService.jobs.create({
        name: values.name,
        type: 'training',
        featureViewId: '1', // 默认使用第一个特征视图
        modelConfig
      });
      
      if (response.success && response.data) {
        message.success('训练任务创建成功');
        setCreateModalVisible(false);
        createForm.resetFields();
        setUseBaselineModel(false);
        setSelectedBaselineModel(null);
        await loadInitialData();
        // 打开新创建的任务
        setCurrentJob(response.data);
        setActiveTab('1'); // 切换到模型训练页签
      } else {
        message.error(response.error || '创建任务失败');
      }
    } catch (error) {
      message.error('创建任务失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 运行任务
  const handleRunJob = async (job: Job) => {
    try {
      setLoading(true);
      // 运行任务
      const response = await mockService.jobs.run(job.id);
      if (response.success) {
        message.success('任务已启动');
        // 更新当前任务状态为运行中
        if (currentJob && currentJob.id === job.id) {
          const updatedJob = { ...currentJob, status: 'running' as const };
          setCurrentJob(updatedJob);
          setLogs(updatedJob.logs || []);
        }
        await loadInitialData();
      } else {
        message.error(response.error || '启动任务失败');
      }
    } catch (error) {
      message.error('启动任务失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 停止任务
  const handleStopJob = async (jobId: string) => {
    try {
      setLoading(true);
      // 停止任务
      const response = await mockService.jobs.stop(jobId);
      if (response.success) {
        message.success('任务已停止');
        await loadInitialData();
      } else {
        message.error(response.error || '停止任务失败');
      }
    } catch (error) {
      message.error('停止任务失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 处理文件上传
  const handleFileUpload = (info: any) => {
    if (info.file.status === 'done') {
      setScriptFile(info.file.originFileObj);
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };

  // 模型训练页签内容
  const renderTrainingTab = () => {
    if (currentJob) {
      // 显示画布编辑界面
      return (
        <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 200px)' }}>
          {/* 顶部工具栏 */}
          <Card size="small" style={{ marginBottom: '16px' }}>
            <Space>
              <Button onClick={() => setCurrentJob(null)}>返回列表</Button>
              <Text strong>{currentJob.name}</Text>
              <Tag color={currentJob.status === 'completed' ? 'green' : currentJob.status === 'running' ? 'blue' : 'default'}>
                {currentJob.status === 'completed' ? '已完成' : currentJob.status === 'running' ? '运行中' : '待执行'}
              </Tag>
              {currentJob.status === 'running' && (
                <Progress percent={60} size="small" style={{ width: '200px' }} />
              )}
              <Space>
                {currentJob.status === 'pending' && (
                  <Button 
                    type="primary" 
                    icon={<PlayCircleOutlined />} 
                    onClick={() => handleRunJob(currentJob)}
                    loading={loading}
                  >
                    运行
                  </Button>
                )}
                {currentJob.status === 'running' && (
                  <Button 
                    danger 
                    icon={<PauseOutlined />} 
                    onClick={() => handleStopJob(currentJob.id)}
                    loading={loading}
                  >
                    停止
                  </Button>
                )}
              </Space>
            </Space>
          </Card>
          
          {/* 主要内容区域 */}
          <div style={{ display: 'flex', flex: 1, gap: '16px', overflow: 'hidden' }}>
            {/* 左侧组件列表 */}
            <Card title="组件库" style={{ width: '250px' }}>
              <div>数据源</div>
              <div>数据预处理</div>
              <div>特征工程</div>
              <div>模型训练</div>
              <div>模型评估</div>
            </Card>
            
            {/* 中间画布 */}
            <Card style={{ flex: 2, overflow: 'auto' }}>
              <FeatureFlowCanvas
                flowData={flowData}
                onFlowChange={handleFlowChange}
                logs={logs}
              />
            </Card>
            
            {/* 右侧YAML显示和日志 */}
            <Card title="配置文件" style={{ width: '300px' }}>
              <Tabs defaultActiveKey="1">
                <TabPane tab="YAML" key="1">
                  <div style={{ 
                    background: '#f5f5f5', 
                    padding: '12px', 
                    borderRadius: '4px',
                    fontFamily: 'monospace',
                    fontSize: '12px',
                    maxHeight: '300px',
                    overflowY: 'auto',
                    whiteSpace: 'pre-wrap'
                  }}>
                    {yamlContent || '# 在这里显示YAML配置'}
                  </div>
                </TabPane>
                <TabPane tab="日志" key="2">
                  <div style={{ 
                    background: '#001529', 
                    color: '#fff', 
                    padding: '12px', 
                    borderRadius: '4px',
                    fontFamily: 'monospace',
                    fontSize: '12px',
                    maxHeight: '300px',
                    overflowY: 'auto'
                  }}>
                    {logs.length === 0 ? (
                      <Text type="secondary" style={{ color: '#888' }}>暂无日志</Text>
                    ) : (
                      logs.map((log, index) => (
                        <div key={index} style={{ marginBottom: '4px' }}>{log}</div>
                      ))
                    )}
                  </div>
                </TabPane>
              </Tabs>
            </Card>
          </div>
        </div>
      );
    }
    
    // 显示任务列表
    return (
      <Card>
        <div className="section-header">
          <Title level={4}>模型训练任务</Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateJob}>
            创建训练任务
          </Button>
        </div>
        
        <Text type="secondary">
          管理模型训练任务，支持可视化编排和自定义脚本两种模式
        </Text>
        
        <Divider />
        
        <Table
          dataSource={jobs}
          columns={[
            {
              title: '任务名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '特征视图',
              dataIndex: 'featureViewId',
              key: 'featureViewId',
              render: (_, record) => {
                const featureView = featureViews.find(fv => fv.id === record.featureViewId);
                return featureView?.name || record.featureViewId;
              }
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: (status: string) => {
                const statusMap: Record<string, { color: string; text: string }> = {
                  pending: { color: 'default', text: '待执行' },
                  running: { color: 'processing', text: '运行中' },
                  completed: { color: 'success', text: '已完成' },
                  failed: { color: 'error', text: '失败' },
                };
                const statusInfo = statusMap[status] || statusMap.pending;
                return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
              },
            },
            {
              title: '模型类型',
              dataIndex: ['modelConfig', 'modelType'],
              key: 'modelType',
            },
            {
              title: '创建时间',
              dataIndex: 'createdAt',
              key: 'createdAt',
              render: (date: string) => formatDateTime(date),
            },
            {
              title: '操作',
              key: 'action',
              render: (_: any, record: Job) => (
                <Space size="middle">
                  <Button type="link" onClick={() => {
                    setCurrentJob(record);
                  }}>编辑</Button>
                  {record.status === 'pending' && (
                    <Button 
                      type="link" 
                      icon={<PlayCircleOutlined />} 
                      onClick={() => handleRunJob(record)}
                      loading={loading}
                    >
                      运行
                    </Button>
                  )}
                  {record.status === 'running' && (
                    <Button 
                      type="link" 
                      danger 
                      icon={<PauseOutlined />} 
                      onClick={() => handleStopJob(record.id)}
                      loading={loading}
                    >
                      停止
                    </Button>
                  )}
                  <Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
                </Space>
              ),
            },
          ]}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>
    );
  };
  
  // 训练详情页签内容
  const renderTrainingDetailsTab = () => {
    return (
      <Row gutter={16} style={{ height: 'calc(100vh - 200px)' }}>
        {/* 左侧任务列表 */}
        <Col span={8}>
          <Card title="训练任务列表" style={{ height: '100%', overflow: 'auto' }}>
            <JobList
              jobs={jobs.filter(job => job.type === 'training')}
              loading={loading}
              onEdit={(job) => {
                setSelectedJob(job);
                setCurrentJob(job);
              }}
              onRun={handleRunJob}
              onStop={handleStopJob}
              onDelete={(jobId) => {
                message.info('删除功能待实现');
              }}
              onSelect={(job) => setSelectedJob(job)}
              selectedJobId={selectedJob?.id}
            />
          </Card>
        </Col>
        
        {/* 右侧详情展示 */}
        <Col span={16}>
          {selectedJob ? (
            <Card title="训练详情" extra={
              selectedJob.status === 'completed' && (
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />} 
                  onClick={() => {
                    // 设置表单初始值
                    modelForm.setFieldsValue({
                      name: `${selectedJob.name}_model`,
                      version: 1,
                      description: `基于${selectedJob.name}训练任务保存的模型`
                    });
                    setShowSaveModelModal(true);
                  }}
                >
                  保存为模型
                </Button>
              )
            }>
              <Text type="secondary">查看模型训练任务的详细信息和配置</Text>
              <Divider />
              <div>
                <Title level={5}>任务信息</Title>
                <div>任务名称: {selectedJob.name}</div>
                <div>状态: {selectedJob.status === 'completed' ? '已完成' : selectedJob.status === 'running' ? '运行中' : selectedJob.status === 'pending' ? '待执行' : selectedJob.status}</div>
                <div>创建时间: {formatDateTime(selectedJob.createdAt)}</div>
                <div>更新时间: {formatDateTime(selectedJob.updatedAt)}</div>
                
                <Divider />
                <Title level={5}>模型配置</Title>
                <div style={{ marginBottom: '12px' }}>
                  <Text strong>训练方式: </Text>
                  <Text>{selectedJob.modelConfig.baselineModel ? `基于基线模型: ${selectedJob.modelConfig.baselineModel}` : '从头开始训练'}</Text>
                </div>
                <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px' }}>
                  {JSON.stringify(selectedJob.modelConfig, null, 2)}
                </pre>
                
                {selectedJob.metrics && (
                  <>
                    <Divider />
                    <Title level={5}>评估指标</Title>
                    <Space wrap>
                      {Object.entries(selectedJob.metrics).map(([key, value]) => (
                        <Tag key={key} color="blue">
                          {key}: {typeof value === 'number' ? value.toFixed(4) : value}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </div>
            </Card>
          ) : (
            <Card title="训练详情">
              <Text type="secondary">请从左侧任务列表中选择一个训练任务查看详情</Text>
            </Card>
          )}
        </Col>

        {/* 保存模型模态框 */}
        <Modal
          title="保存模型"
          open={showSaveModelModal}
          onCancel={() => setShowSaveModelModal(false)}
          footer={null}
          width={600}
        >
          <Form
            form={modelForm}
            layout="vertical"
            onFinish={handleSaveModel}
          >
            <Form.Item 
              name="name" 
              label="模型名称" 
              rules={[{ required: true, message: '请输入模型名称' }]}
            >
              <Input placeholder="请输入模型名称" />
            </Form.Item>
            <Form.Item 
              name="version" 
              label="版本号"
              rules={[{ required: true, message: '请输入版本号' }]}
            >
              <Input placeholder="请输入版本号" type="number" min={1} />
            </Form.Item>
            <Form.Item 
              name="description" 
              label="模型描述"
            >
              <Input.TextArea rows={4} placeholder="请输入模型描述" />
            </Form.Item>
            <div style={{ textAlign: 'right' }}>
              <Button onClick={() => setShowSaveModelModal(false)} style={{ marginRight: '10px' }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                保存模型
              </Button>
            </div>
          </Form>
        </Modal>
      </Row>
    );
  };
  
  // 训练日志页签内容
  const renderTrainingLogsTab = () => {
    return (
      <Row gutter={16} style={{ height: 'calc(100vh - 200px)' }}>
        {/* 左侧任务列表 */}
        <Col span={8}>
          <Card title="训练任务列表" style={{ height: '100%', overflow: 'auto' }}>
            <JobList
              jobs={jobs.filter(job => job.type === 'training')}
              loading={loading}
              onEdit={(job) => {
                setSelectedJob(job);
                setCurrentJob(job);
              }}
              onRun={handleRunJob}
              onStop={handleStopJob}
              onDelete={(jobId) => {
                message.info('删除功能待实现');
              }}
              onSelect={(job) => {
                setSelectedJob(job);
                // 更新当前显示的日志
                if (job.logs) {
                  setLogs(job.logs);
                }
              }}
              selectedJobId={selectedJob?.id}
            />
          </Card>
        </Col>
        
        {/* 右侧日志展示 */}
        <Col span={16}>
          {selectedJob ? (
            <Card title={`训练日志 - ${selectedJob.name}`}>
              <Text type="secondary">实时查看模型训练过程中的日志信息</Text>
              <Divider />
              <div style={{ 
                background: '#001529', 
                color: '#fff', 
                padding: '16px', 
                borderRadius: '4px',
                fontFamily: 'monospace',
                fontSize: '14px',
                minHeight: '400px',
                maxHeight: '600px',
                overflowY: 'auto'
              }}>
                {selectedJob.logs && selectedJob.logs.length > 0 ? (
                  selectedJob.logs.map((log, index) => (
                    <div key={index} style={{ marginBottom: '4px' }}>{log}</div>
                  ))
                ) : (
                  <Text type="secondary" style={{ color: '#888' }}>暂无日志信息</Text>
                )}
              </div>
            </Card>
          ) : (
            <Card title="训练日志">
              <Text type="secondary">请从左侧任务列表中选择一个训练任务查看日志</Text>
            </Card>
          )}
        </Col>
      </Row>
    );
  };

  return (
    <Layout className="training-page">
      <style>
        {`
          .selected-row {
            background-color: #e6f7ff;
          }
          
          .selected-row:hover {
            background-color: #e6f7ff !important;
          }
        `}
      </style>
      <Content>
        <Card>
          <div className="section-header">
            <Title level={4}>模型训练</Title>
          </div>
          
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            items={[
              {
                key: '1',
                label: <span><ToolOutlined /> 模型训练</span>,
                children: renderTrainingTab()
              },
              {
                key: '2',
                label: <span><FileTextOutlined /> 训练详情</span>,
                children: renderTrainingDetailsTab()
              },
              {
                key: '3',
                label: <span><FileTextOutlined /> 训练日志</span>,
                children: renderTrainingLogsTab()
              }
            ]}
          />
        </Card>

        {/* 创建任务模态框 */}
        <Modal
          title="创建训练任务"
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            createForm.resetFields();
            setUseBaselineModel(false);
            setSelectedBaselineModel(null);
          }}
          footer={null}
          width={600}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreateSubmit}
          >
            <Form.Item
              name="name"
              label="任务名称"
              rules={[{ required: true, message: '请输入任务名称' }]}
            >
              <Input placeholder="请输入任务名称" />
            </Form.Item>
            
            <Form.Item label="训练模式">
              <Radio.Group 
                value={trainingMode} 
                onChange={(e) => setTrainingMode(e.target.value)}
              >
                <Radio value="visual">可视化编排</Radio>
                <Radio value="advanced">高级模式（上传脚本）</Radio>
              </Radio.Group>
            </Form.Item>
            
            <Form.Item label="模型初始化">
              <Radio.Group 
                value={useBaselineModel ? 'baseline' : 'scratch'}
                onChange={(e) => setUseBaselineModel(e.target.value === 'baseline')}
              >
                <Radio value="scratch">从头开始训练</Radio>
                <Radio value="baseline">基于已有模型</Radio>
              </Radio.Group>
            </Form.Item>
            
            {useBaselineModel && (
              <Form.Item 
                label="选择基线模型" 
                name="baselineModel"
                rules={[{ required: true, message: '请选择基线模型' }]}
              >
                <Select 
                  placeholder="请选择基线模型"
                  onChange={(value) => setSelectedBaselineModel(value)}
                >
                  {models.map(model => (
                    <Option key={model.id} value={model.name}>
                      {model.name} (v{model.version})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            )}
            
            {trainingMode === 'advanced' && (
              <Form.Item label="上传训练脚本">
                <Upload 
                  beforeUpload={() => false} 
                  onChange={handleFileUpload}
                  maxCount={1}
                >
                  <Button icon={<UploadOutlined />}>选择文件</Button>
                </Upload>
                {scriptFile && <Text type="secondary">{scriptFile.name}</Text>}
              </Form.Item>
            )}

            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading}>
                  创建
                </Button>
                <Button onClick={() => {
                  setCreateModalVisible(false);
                  createForm.resetFields();
                }}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Content>
    </Layout>
  );
};

export default TrainingPage;